#!/bin/sh

e2e_test_install() {
  init_expandable_storage_class

  create_or_replace_cluster "$CLUSTER_NAME" "$CLUSTER_NAMESPACE" 2 \
    --set cluster.pods.persistentVolume.storageClass="$EXPANDABLE_STORAGE_CLASSNAME"

  wait_pods_running "$CLUSTER_NAMESPACE" 2
  wait_cluster "$CLUSTER_NAME" "$CLUSTER_NAMESPACE"
}

e2e_test() {
  run_test "Checking that data dir permissions are set correctly" check_data_dir_permissions_are_set_correctly

  run_test "If the configured volume size is 128Mi the persistent volume claim capacity should 128Mi" check_persistent_volume_claim_size

  run_test "Checking that pods shared memory is bigger than 64M" check_shared_memory

  run_test "Checking that JIT is working" check_jit

  run_test "Checking that PVC is updated in the StatefulSet" check_persistent_volume_claim_is_updated
}

check_data_dir_permissions_are_set_correctly() {
  kubectl exec -n "$CLUSTER_NAMESPACE" "$CLUSTER_NAME-0" -c patroni -- chmod 777 /var/lib/postgresql/data
  kubectl exec -n "$CLUSTER_NAMESPACE" "$CLUSTER_NAME-1" -c patroni -- chmod 777 /var/lib/postgresql/data
  kubectl delete pod -n "$CLUSTER_NAMESPACE" "$CLUSTER_NAME-0" "$CLUSTER_NAME-1"
  wait_pods_running "$CLUSTER_NAMESPACE" 2
  wait_cluster "$CLUSTER_NAME" "$CLUSTER_NAMESPACE"
}

check_persistent_volume_claim_size() {
  VOLUME_CLAIM_CAPACITY="$(kubectl get persistentvolumeclaims -n "$CLUSTER_NAMESPACE" \
    "$CLUSTER_NAME-data-$CLUSTER_NAME-0" \
    -o jsonpath='{.spec.resources.requests.storage}')"

  if [ "$VOLUME_CLAIM_CAPACITY" = "128Mi" ]
  then
    success "Volume Size is the requested"
  else
    fail "Volume is not the requested. Actual: $VOLUME_CLAIM_CAPACITY"
  fi 
}

check_shared_memory() {
  SHM_SIZE="$(get_shared_memory)"

  assert_string_not_equal "64M" "$SHM_SIZE"
}

get_shared_memory() {
  kubectl exec -n "$CLUSTER_NAMESPACE" "$CLUSTER_NAME-0" -c patroni  -- df -h > "$LOG_PATH/devices.log"
  grep shm "$LOG_PATH/devices.log" | awk '{print $2}'
}

check_jit() {
  if run_query -i 0 -p 5432 -q "set jit=on; set jit_above_cost = 0.001;  select 1;" > /dev/null
  then
      success "JIT is working as expected"
  else 
      fail "JIT is not working as expected"
  fi
}

check_persistent_volume_claim_is_updated() {
  kubectl patch sgcluster -n "$CLUSTER_NAMESPACE" "$CLUSTER_NAME" \
    --type=merge -p '{"spec":{"pods":{"persistentVolume":{"size":"256Mi"}}}}'

  if wait_until check_persistent_volume_claim "256Mi"
  then
    success "Volume Size is the requested"
  else
    fail "Volume is not the requested. Actual: $VOLUME_CLAIM_CAPACITY"
  fi 
}

check_persistent_volume_claim() {
  local EXPECTED_CAPACITY="$1"
  VOLUME_CLAIM_CAPACITY="$(wait_until kubectl get sts -n "$CLUSTER_NAMESPACE" \
    "$CLUSTER_NAME" \
    -o jsonpath='{.spec.volumeClaimTemplates[0].spec.resources.requests.storage}')"

  [ "$VOLUME_CLAIM_CAPACITY" = "$EXPECTED_CAPACITY" ]
}
